<template>
  <div id="workAdd" class="wrapper px-4 pt-4 scrollY" >
    <table class="w-100  ur-table" border="1" style="border: 1px solid #0D2264">
    <tr height="50" v-show="workEdit">
      <td class="px-2 140 text-right">创建人：</td>
      <td class="px-2">
        <el-input class="w-100" size="small" v-model="work.Creator" disabled></el-input>
      </td>
      <td class="px-2 140 text-right">工单任务号：</td>
      <td class="px-2">
        <el-input class="w-100" size="small" v-model="work.No"></el-input>
      </td>
    </tr>
    <tr height="50" v-show="!workEdit">
      <td class="px-2 140 text-right">工单任务号：</td>
      <td class="px-2" colspan="3">
        <el-input class="w200" size="small" v-model="work.No"></el-input>
        <label class="text-danger ml-2">备：可不填写，系统会自动生成任务号</label>
      </td>
    </tr>
    <tr height="50">
      <td class="px-2 140 text-right">* 工单分类：</td>
      <td class="px-2">
        <el-select  class="w-100" size="small" v-model="work.Classify" @change="classifyChange">
          <el-option v-for="(item,index) in global.WorkTypes" :key="index" :label="item" :value="index"></el-option>
        </el-select>
      </td>
      <td class="px-2 140 text-right">* 来源信息：</td>
      <td class="px-2">
        <el-select class="w-100" size="small" v-model="work.Source"><!--WorkSources-->
          <el-option v-for="(item,index) in global.FaultSources" v-if="item.no!=2" :key="index+1" :label="item.name" :value="item.no"></el-option>
        </el-select>
      </td>
    </tr>
<!--      [1,2,3,4,6]-->
    <tr height="50" v-if="[1,5].indexOf(work.Classify)!=-1">
      <td class="px-2 w140 text-right">设施编号：</td>
      <td class="p-2" colspan="3">
        <el-input class="w-100" size="small" v-model="devNo"></el-input>
      </td>
    </tr>
    <tr height="50">
      <td class="px-2 w140 text-right">* 工单级别：</td>
      <td class="px-2">
        <el-select class="w-100" size="small" v-model="work.Level">
          <el-option v-for="(item,index) in global.WorkLevels" :key="index+1" :label="item" :value="index+1"></el-option>
        </el-select>
      </td>
      <td class="px-2 w140 text-right">* 指派责任区：</td>
      <td class="px-2">
        <el-tooltip :content="errors.first('assignedAreaId')" :value="errors.has('assignedAreaId')" :manual="true">
          <el-select class="w-100" size="small" v-model="work.AssignedAreaId" @change="getUsers" :class="{'is-error':errors.has('assignedAreaId')}" name="assignedAreaId">
            <el-option label="请选择" :value="0"></el-option>
            <el-option v-for="(item,index) in areas" :key="index" :label="item.Name" :value="item.Id"></el-option>
          </el-select>
        </el-tooltip>
      </td>
    </tr>
    <tr height="50">
        <td class="px-2 w140 text-right">指派处理人：</td>
        <td class="px-2">
          <el-tooltip :content="errors.first('assignedUserId')" :value="errors.has('assignedUserId')" :manual="true">
            <el-select class="w-100" size="small" v-model="assignedUserId" @change="selUser" :disabled="work.workState==0||work.workState==10" :class="{'is-error':errors.has('assignedUserId')}" name="assignedUserId">
              <el-option label="请选择" :value="0" ></el-option>
              <el-option v-for="(item,index) in users" :key="index+1" :label="item.Name" :value="item.Id"></el-option>
            </el-select>
          </el-tooltip>
        </td>
        <td class="px-2 w150 text-right">工单接收人号码：</td>
        <td class="px-2">
          <el-tooltip :content="errors.first('SmsPhone')" :value="errors.has('SmsPhone')" :manual="true">
            <el-input :disabled="work.workState==0||work.workState==10" class="w-100" size="small" v-model="smsPhone" :class="{'is-error':errors.has('SmsPhone')}" v-validate="'smsPhone'" name="SmsPhone"></el-input>
          </el-tooltip>
        </td>
      </tr>
    <tr height="50">
      <td class="px-2 w140 text-right">来电人：</td>
      <td class="px-2"><el-input class="w-100" size="small" v-model="work.ReportUser"></el-input></td>
      <td class="px-2 w140 text-right">来电号码：</td>
      <td class="px-2">
        <el-tooltip :content="errors.first('ReportPhone')" :value="errors.has('ReportPhone')" :manual="true">
          <el-input class="w-100" size="small" v-model="work.ReportPhone" :class="{'is-error':errors.has('ReportPhone')}" v-validate="'phone'" name="ReportPhone"></el-input>
        </el-tooltip>
      </td>
    </tr>
    <tr height="50">
      <td class="px-2 w140 text-right">* 派遣时间：</td>
      <td class="px-2">
<!--        <el-date-picker type="date"  class="w150" size="small" value-format="yyyy-MM-dd" v-model="work.StartTime"></el-date-picker>-->
        <el-tooltip :content="errors.first('StartTime')" :value="errors.has('StartTime')" :manual="true">
          <el-date-picker v-model="work.StartTime" type="datetime" size="small" value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" class="w-100"
          :class="{'is-error':errors.has('StartTime')}" v-validate="'required'" name="StartTime"></el-date-picker>
        </el-tooltip>
      </td>
      <td class="px-2 w140 text-right">* 办理时限：</td>
      <td class="px-2">
        <el-tooltip :content="errors.first('endTime')" :value="errors.has('endTime')" :manual="true">
<!--          <el-date-picker type="date"  :class="{'is-error':errors.has('endTime')}" class="w150" size="small" v-model="work.EndTime" value-format="yyyy-MM-dd" name="endTime" @change="validate($event)" ></el-date-picker>-->
          <el-date-picker v-model="work.EndTime" type="datetime"  value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期时间" size="small" class="w-100"
          :class="{'is-error':errors.has('endTime')}" name="endTime" @change="validate($event)"></el-date-picker>
        </el-tooltip>
      </td>
    </tr>
    <tr height="50">
      <td class="px-2 w140 text-right">* 工单内容：</td>
      <td class="p-2" colspan="3">
        <el-tooltip :content="errors.first('content')" :value="errors.has('content')" :manual="true">
          <el-input resize="none" type="textarea" rows="3"  v-model="work.Content" :class="{'is-error':errors.has('content')}" v-validate="'required|max:511'" name="content"></el-input>
        </el-tooltip>

      </td>
    </tr>
    <tr height="50">
      <td class="px-2 w140 text-right">上传图片：</td>
      <td class="px-2" colspan="3">
        <input type="file" style="line-height: 20px;"  multiple="multiple" accept=".png,.jpg,jpeg" @change="changeFiles">
        <el-button size="small"  class="ur-btn-round ur-btn float-right ur-btn-primary " v-if="files.length"  @click="showCarousel=true">
          <i class="iconfont icon-xianshi txt_blue2"></i>图片预览
        </el-button>
      </td>
    </tr>
    <tr height="50" v-show="workEdit">
      <td class="px-2 w140 text-right">处理结果：</td>
      <td class="px-2" >
        <!--WorkOrderState-->
        <el-select class="w150" size="small" v-model="work.workState" @change="stateChange">
          <el-option label="已完成" :value="10"></el-option>
          <el-option label="待指派" :value="0"></el-option>
          <el-option label="待处理" :value="1"></el-option>
        </el-select>
      </td>
      <td class="px-2 w140 text-right">操作说明：</td>
      <td class="px-2" >
        <el-input class="w150" size="small" v-model="proContent"></el-input>
      </td>
    </tr>
  </table>
    <div class="my-3 text-center">
      <el-button class="ur-btn ur-btn-primary" @click="save"><i class="iconfont icon-sure"></i>确定</el-button>
      <el-button class="ur-btn ur-btn-primary" @click="close"><i class="iconfont icon-close3"></i>取消</el-button>
    </div>
    <!--图片预览-->
    <div class="w-100"  v-show="showCarousel" style="position: absolute;background: rgba(0,0,0,.4);top:48px;left: 0;height: 610px;">
<!--      -->
      <file-read :fileDelBtn="limits.indexOf('3_01_01_07')!=-1" :devId="work.Id" :files="files" :type="'work'" :delFileUrl="'/SHWorkorder/DelWorkFiles'" @closeFileRead="closeFileRead"></file-read>
<!--      <el-image class="w-100 h-100" :src="fileURL[0]" :preview-src-list="fileURL" ></el-image>-->
<!--      <i @click="showCarousel=false" class="iconfont icon-false font24" style="position: absolute;right: 5px;top:10px;opacity: 0.8;"></i>-->
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import api from 'api/api'
  import receiptList from './receipt-list'
  import fileRead from "base/fileRead/fileRead2"
  import {mapState} from 'vuex'

  export default {
    components: {receiptList,fileRead},
    props: {
      workEdit:false,
      work:{Classify:1,Source:1,Level:1,AssignedAreaId:'',AssignedUserId:''}
    },
    data() {
      return {
        tableData: [
          {label1:'* 工单分类：', value1: 'Classify',label2:'* 来源信息：', value2: 'workSource'},
          {label1:'* 工单级别：', value1: 'level',label2:'工单接收人号码：', value2: 'recipientPhone'},
          {label1:'来电人：', value1: 'caller',label2:'来电号码：', value2: 'callPhone'},
          {label1:'* 指派责任区：', value1: 'acceptArea',label2:'指派处理人：', value2: 'acceptUser'},
          {label1:'* 开始时间：', value1: 'createTime',label2:'* 结束时间：', value2: 'endTime'},
          {label1:'* 工单了内容：', value1: 'content'},
          {label1:'上传图片：', value1: 'file'},
        ],
        devNo:'',
        source:2,
        areas:[],
        users:[],
        userId:0,
        server:api.ajaxServe,
        showCarousel:false,
        formData:new FormData(),
        height:0,
        files:[],
        fileURL:[],
        assignedUserId:0,
        smsPhone:'',
        proContent:''//特殊操作 操作说明
      }
    },
    watch: {},
    computed: {
      ...mapState({
        userType:state=>state.user.userInfo.userType,
        limits:state=>state.user.userInfo.limits
      })
    },
    methods: {
      closeFileRead(v){
        this.showCarousel=false
      },
      validate(value){
        let total = new Date(value) - new Date(this.work.StartTime)
        if (this.$validator.errors.has('endTime')) {
          this.$validator.errors.remove('endTime')
        }
        if (total < 0 || value == '') {
          this.$validator.errors.add({
            field: 'endTime',
            msg: '结束时间必填且不能小于开始日期'
          })
          return false
        } else {
          this.$validator.errors.remove('EndTime')
          return true
        }
      },
      validateAreaId(value,name,msg){
        if (value == 0) {
          if (this.$validator.errors.has(name)) {
            this.$validator.errors.remove(name)
          }
          this.$validator.errors.add({
            field: name,
            msg: msg
          })
          return false
        } else {
          this.$validator.errors.remove(name)
          return true
        }
      },
      classifyChange(val) {
        if (val==1) {//灯不亮
          this.source = 2
        } else if (val == 5) {//配电柜
          this.source = 1
        } else {
          this.source = 0
          this.devNo = ''
        }
      },
      receiptDialog(v){
        this.queryWorkById()
        this.$emit('receiptDialog',{showWorkDeal:false,showReceipt:true,isAdd:v.isAdd})
      },
      changeFiles(event){
        let files=event.target.files
        for(let i=0;i<files.length;i++){
          this.formData.append('files',files[i])
        }
      },
      stateChange(state){
        this.$set(this.work,'workState',state)
        if(state==0){//待指派
          this.assignedUserId=0
          this.smsPhone=''
        }else if(state==1){
          if(this.work.AssignedUserId){
            this.assignedUserId=this.work.AssignedUserId
          }else{
            this.assignedUserId=this.users[0]['Id']
          }
          this.selUser(this.assignedUserId)
        }else if(state==10){
          if(this.work.AssignedUserId){
            this.assignedUserId=this.work.AssignedUserId
          }
          this.selUser(this.assignedUserId)
        }
      },
      save(){
        if (this.assignedUserId != '') this.work.AssignedUserId = this.assignedUserId
        if (this.smsPhone != '') this.work.SmsPhone = this.smsPhone
        //工单分类选择1、5时设施编号没填则source传0
        let url = '/SHWorkorder/Create?source=' + (this.devNo == '' ? 0 : this.source )+ '&devNo=' + (this.devNo == '' ? 0 : this.devNo)
        if (this.work.Id){
          this.work.WorkOrderState = this.work.workState
          this.work.devNo = this.devNo
          url = '/SHWorkorder/UpdateWorks?proContent=' + this.proContent
        }
        let res=this.validate(this.work.EndTime)
        let res2=this.validateAreaId(this.work.AssignedAreaId,'assignedAreaId','请选择责任区')
        let res3=true
        if(this.work.workState==1){
          res3=this.validateAreaId(this.assignedUserId,'assignedUserId','请选择')
        }
        if (!res||!res2||!res3) return
        this.$validator.validateAll().then((res) => {
          if (res) {
            api.fetch(url, this.work)
              .then(async r => {
                if (this.formData.getAll('files').length) {
                  await this.uploadFiles(r)
                } else {
                  this.$emit('workAddDialog')
                }
              })
          }
        })
      },
      close(){
        this.$emit('workAddDialog')
      },
      uploadFiles(id){
        api.httpFormData('/SHWorkorder/SaveWorkFiles?workId='+id,this.formData)
          .then(r=>{
            this.$emit('workAddDialog')
          })
      },
      delFile(file,index){//删除工单附件
        this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
          .then(() => {
            api.fetchSimple('/SHWorkorder/DelWorkFiles',{workId:this.work.Id,fileIds:[file.Id]})
              .then(r=>{
                this.files.splice(index,1)
                if(this.files.length==0) this.showCarousel=false
              })
          })
      },
      queryWorkById(){
        api.fetchSimple('/SHWorkorder/QueryWorkDetail?worderId='+this.work.Id,{})
          .then(r=>{
            this.files=r.files?r.files:[]
            for(let i=0;i<this.files.length;i++){
              this.fileURL.push(api.ajaxServe+this.files[i].OriginUrl)
            }
          })
      },
      queryArea(){
        api.fetchSimple('/ViewInfo/QueryRegionsForTree').then(r=>{
          this.getAllRegion(r)
        })
      },
      getAllRegion(areas){
        if(areas.length==0) return
        areas.map(o=>{
         this.areas.push(o);
         if(o.Childs.length){
           this.getAllRegion(o.Childs)
         }
        })
      },
      getUsers(areaId){
        if(areaId==0){
          this.users=[]
          this.work.AssignedUserId=''
        }
        this.validateAreaId(areaId,'assignedAreaId','请选择责任区')
        if(this.work.workState==0||this.work.workState==10) return
        api.fetchSimple('/User/QueryByRegions',{regionId:areaId})
          .then(r=>{
            this.users = r
            let obj = {}
            r.map(o => obj[o.Id] = o)
            if (!obj[this.assignedUserId]) {
              this.assignedUserId = r[0].Id
            }
          })
      },
      selUser(userId){
        // if(this.work.workState==1){
        //   this.validateAreaId(this.assignedUserId,'assignedUserId','请选择')
        // }
        this.users.map(r=>{
          if(r.Id==userId){
            this.smsPhone=r.Mobile
          }
        })
      }
    },
    created() {
      if(this.work.Id){//查询工单附件、操作历史、回执信息
        this.assignedUserId=this.work.AssignedUserId
        this.smsPhone=this.work.SmsPhone
        this.queryWorkById()
        this.$set(this.work,'workState',1)//特殊操作
        this.devNo=this.work.DevNo
      }else{
        this.$set(this.work,'StartTime',api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss'))
        this.$set(this.work,'EndTime',api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss'))
      }
      this.queryArea()
      if(this.work.AssignedAreaId){//加载责任区下用户
        this.getUsers(this.work.AssignedAreaId)
      }
    },
    mounted() {
      // this.height=this.workEdit?615:570
      this.height=570
    }
  }
</script>
<style  lang="stylus" rel="stylesheet/stylus">
  #workAdd{
    /*.carousel_wrap{width: 650px;position: absolute;top:50%;left: 50%;margin-left: -325px;margin-top: -150px;}*/
    /*.el-carousel__item{text-align: center;line-height: 300px;}*/
  }
</style>
